package cn.ticsmyc.tools.framework.mvc;

import cn.ticsmyc.tools.framework.ioc.context.ClassPathXmlApplicationContext;
import cn.ticsmyc.tools.framework.ioc.io.Resource;
import cn.ticsmyc.tools.framework.ioc.io.ResourceLoader;
import cn.ticsmyc.tools.framework.mvc.annotation.Controller;
import cn.ticsmyc.tools.packageScan.PackageScaner;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;

/**
 * @author Ticsmyc
 * @date 2021-05-26 16:39
 */
public class DispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();
    private ClassPathXmlApplicationContext applicationContext;

    @Override
    public void init(ServletConfig config) throws ServletException {
        applicationContext = new ClassPathXmlApplicationContext("application-annotation.xml");
        doLoadConfig(config);
        doScannerAndInstance(properties.getProperty("scanPackage"));

    }

    private void doScannerAndInstance(String scanPackage) {
        Set<Class<?>> classes = PackageScaner.getClasses(scanPackage);
        for(Class<?> clazz : classes){
            if(clazz.isAnnotationPresent(Controller.class)){
                //处理注解
            }
        }
    }


    private void doLoadConfig(ServletConfig config) {
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        ResourceLoader resourceLoader = new ResourceLoader();
        Resource resource = resourceLoader.getResource(contextConfigLocation);
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
    }
}
